package com.yanxu.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/29-2025
 * @Description: AtomicInteger  的基本使用。
 * 使用了原子类之后，不需要加锁，也可以保证线程安全问题。
 */
public class AtomicIntegerDemo1 {
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    private static volatile int basicCount = 0;

    public static void incrementAtomic() {
        atomicInteger.getAndIncrement();  //进行加 1 操作
        //atomicInteger.getAndDecrement();  //进行减 1 操作
        //atomicInteger.getAndAdd(10);  // 进行加操作，可以传递一个参数值， 该值可以是 正数(进行加操作)，  该值可以是 负数(进行减操作)
    }

    public static void incrementBasic() {
        basicCount++;
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        for (int i = 0; i < 10000; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        incrementAtomic();
                        incrementBasic();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }

        countDownLatch.await();
        System.out.println("atomic 计算结果" + atomicInteger.get());
        System.out.println("普通的计算结果" + basicCount);
        executorService.shutdown();
    }
}